<template>
  <div class="agent" v-loading="loading">
    <div class="top">
      <div class="contition">
        <div class="wrap_time">
          <date-time type="other_half_hour" ref="child" :query="query" :isTimePeriod = "true" :isOther="true"></date-time>
          <el-button type="primary" class="primary_btn fr find" v-on:click.stop="search">{{$t('public.search2')}}</el-button>
          <div class="clear"></div></div>
      </div>
      <affix :label="cityName.name.split('(')[0] + $t('report.agentWorkLoRe')"></affix>
    </div>
    <div :id="id">
      <el-row class="ichars">
        <highcharts :options="highchartsOptions"></highcharts>
        <div class="notes">
          <span class="light">{{$t('report.hicharsNotes')}}: <span></span>{{$t('report.hicharsLight')}}</span>
          <span class="dark"><span></span>{{$t('report.hicharsDark')}}</span>
        </div>
      </el-row>
      <div class="tab">
        <div class="export">
          <el-button class="primary_btn fr" v-on:click.stop="config" v-if="!configHeaderBool">{{$t('report.setHeaderConfig')}}</el-button>

          <!-- <el-button class="primary_btn fr report_excel_btn"
            v-if="$store.getters.exportFromEnd"
            v-on:click.stop="exportExcel"
          >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->

          <el-button class="primary_btn fr report_excel_btn"
            v-on:click.stop="exportXlsx"
          >{{$t('report.exportXls')}}</el-button>

          <el-button class="primary_btn fr pdf" v-on:click.stop="exportPdf">{{$t('report.exportPDF')}}</el-button>
          <el-button class="primary_btn fr pdf" v-on:click.stop="flag">{{$t('report.returnPreviousPage')}}</el-button>
        </div>
        <div class="deploy">
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{$t('report.toggleInstructe')}}</span>
              </template>
              <div>
                {{$t('report.callOutNum')}}<br>
                {{$t('report.callOutSucNum')}}<br>
                {{$t('report.callInRingNum')}}<br>
                {{$t('report.callInConnectNum')}}<br>
                {{$t('report.callInConnectRate')}}<br>
                {{$t('report.callInTurnNum')}}<br>
                <!-- {{$t('report.callOnlineAllTime')}}<br> -->
                {{$t('report.callInAllTime')}}<br>
                {{$t('report.callInAverTime')}}<br>
                {{$t('report.callOutTotalTime')}}<br>
                {{$t('report.callOutAverTi')}}<br>
                {{$t('report.callOutAverHoursNum')}}<br>
                {{$t('report.employeeRate')}}<br>
                {{$t('report.callBusyTime')}}<br>
                {{$t('report.callRestAllTime')}}<br>
                {{$t('report.callCustomStatusTime')}}<br>
                {{$t('report.systemBusy')}}<br>
                {{$t('report.RingingTimeLength')}}<br>
                {{$t('report.HoldTimeLength')}}<br>
                {{$t('report.ConsultTimeLength')}}<br>
                {{$t('report.ThreeWayCallTimeLength')}}<br>
                21.{{$t('report.callTalkTime')}}<br>
                22.{{$t('report.callOnlineAllTime')}}<br>
                23.{{$t('report.UnansweredCalls')}}<br>
                24.{{$t('report.IntegratedCallRate')}}
                25.{{$t('report.TransferCount')}}<br>
                26.{{$t('report.TransferAcceptRate')}}<br>
                27.{{$t('report.NormalTransferTimeLength')}}<br>
                28.{{$t('report.DialTransferTimeLength')}}<br>
                29.{{$t('report.TransferTimeLength')}}<br>
                30.{{$t('report.IncomingRingingTimeLength')}}<br>
                31.{{$t('report.OutgoingWaitingTimeLength')}}<br>
                32.{{$t('report.MaxCallTimeLength')}}<br>
                33.{{$t('report.HoldSoftphoneTimeLength')}}<br>
                34.{{$t('report.HoldSoftphoneCount')}}<br>
                35.{{$t('report.OutgoingAbandonCount')}}<br>
                36.{{$t('report.RollOutCount')}}<br>
                37.{{$t('report.RepeatCallInBy24hCount')}}<br>
                38.{{$t('report.RepeatCallInBy48hCount')}}<br>
                39.{{$t('report.RedirectAgentDeal')}}<br>
                40.{{$t('report.RedirectAgentNotDeal')}}<br>
                41.{{$t('report.RedirectGroupDeal')}}<br>
                42.{{$t('report.RedirectGroupNotDeal')}}<br>
                43.{{$t('report.onlineStatusTotalDays')}}<br>
                44.{{$t('report.customerHandUpSpeed')}}<br>
                45.{{$t('report.pickPpCount20s')}}<br>
                46.{{$t('report.forwardedCallsReceivedIn20s')}}<br>
                47.{{$t('report.RepeatCallInBy24hCount')}}<br>
                48.{{$t('report.RepeatCallInBy48hCount')}}<br>
                49.{{$t('report.firstSolutionNumber24h')}}<br>
                50.{{$t('report.firstSolutionNumber48h')}}<br>
                51.{{$t('report.firstCallsReceivedNumber24h')}}<br>
                52.{{$t('report.firstCallsReceivedNumber48h')}}<br>
                <p class="custom_alg">{{$t('report.ziDingYi')}}：</p>
                <p v-for="(item, index) in formulas" :key="item.name">
                  {{index + 53}}.{{item.formulaInstr}}
                </p>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <report-table :data="serveNumData" :sum="sum" :config="[...Config, ...customConfig]"> </report-table>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%" :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{$t('report.reportExportTipTitle')}}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{$t('public.cancel')}}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{$t('public.confirm')}}</el-button>
      </span>
    </el-dialog>
    <header-option v-show="isShow" :show="isShow" :option="headOptionsShow" type="call_report_agent_time" v-on:close="close"></header-option>
  </div>
</template>
<script>
  import dateTime from '../base/datetime.vue'
  import {exportReportPdf, checkTime, searchTime, headOptionsToXlsxHeaders, colorConfigArr, mixData} from '@/utils/reportUtils.js'
  import {deepClone, getCallTimeLength, optionTimeTypeCheck} from '@/utils/m7Utils.js'
  import reportTable from '../base/reportTable.vue'
  import headerOption from '../base/headerOption.vue'
  import affix from '../../../ui-modules/affix/Affix.vue'
  import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'

  export default {
    name: 'callReportAgent',
    data () {
      return {
        loading: false, // 查询时展示加载的开关
        query: { // 查询条件时间信息等
        },
        isShow: false, // 是否展示配置表头开关
        dialogVisible: false, // 导出pdf弹窗开关
        headOptions: { // 表头数据
          Config: []
        },
        headOptionsShow: {}, // 配置表头数据
        id: 'query_agent_time', // 查询id
        serverData: [], // 表格数据
        serveNumData: [], // 表格数据
        sum: [], // 表格合计数据
        highchartsDefaultOptions: {
          chart: { type: '', animation: false },
          colors: colorConfigArr,
          xAxis: {
            categories: [],
            title: {
              enabled: true,
              text: '',
              style: { fontWeight: 'normal' }
            }
          },
          yAxis: {
            gridLineColor: '#e6e6e6',
            allowDecimals: false,
            title: { text: '' },
            showEmpty: false
          },
          title: { text: this.$t('report.agentWork') },
          legend: { align: 'center', verticalAlign: 'top', y: 30 },
          tooltip: {
            pointFormat: '<span style="color:{point.color}">\u25CF</span> {series.name}: <b>{point.y}{point.valueSuffix}</b><br/>',
            shared: true
          },
          credits: { enabled: false },
          series: []
        }
      }
    },
    computed: {
      // 判断是否展示配置表头
      configHeaderBool () {
        return this.$store.state.report.setConfigHeaderBool
      },
      // 表头数据
      Config () {
        return this.getConfig(this.headOptions)
      },
      // charts图表数据
      highchartsOptions () {
        let options = deepClone(this.highchartsDefaultOptions)
        if (!this.serverData || this.serverData.length === 0) {
          return options
        }
        let headerConfig = this.Config || []
        let datas = this.serverData
        let categoriesArray = []
        let seriesArray = []

        headerConfig.forEach(item => {
          if (!item.show) {
            return
          }
          let serie = { name: item.displayname, data: [], valueName: item.name }
          if (item.name === 'CallInAcceptCount' || item.name === 'CallInAccessCount' || item.name === 'CallOutAccessCount' || item.name === 'TransferAcceptCount' || item.name === 'CallOutAcceptCount' || item.name === 'AverageHourCallCount') {
            seriesArray.push(serie)
          }
        })
        for (let i = 0; i < datas.length; i++) {
          categoriesArray.push(this.formatChartTime(datas[i]['_id']))
          for (let j = 0; j < seriesArray.length; j++) {
            seriesArray[j].data.push(datas[i][seriesArray[j].valueName])
          }
        }

        options.xAxis.categories = categoriesArray
        options.series = seriesArray

        return options
      }
    },
    methods: {
      // 截取时间渲染
      formatChartTime (reportTime) {
        if (this.query.timeType === 'year') {
          return reportTime.substring(4, 6)
        } else if (this.query.timeType === 'month') {
          return reportTime.substring(6, 8)
        } else if (this.query.timeType === 'day' || this.query.timeType === 'other_half_hour') {
          return reportTime.substring(0, 16)
        }
      },
      // 钻入进来执行的方法
      search1 () {
        this.query = deepClone(this.cityName.queryOne)
        this.$refs.child.query.initShow = this.cityName.queryOne.TimeType
        this.$refs.child.form = {
          timeType: this.cityName.queryOne.TimeType,
          yearReport: parseInt(this.cityName.queryOne.yearReport),
          monthReport: parseInt(this.cityName.queryOne.monthReport),
          dayReport: parseInt(this.cityName.queryOne.dayReport)
        }
        if (this.cityName.dateSource.timeType) {
          this.$refs.child.form.timeType = this.cityName.dateSource.timeType
          this.$refs.child.week = this.cityName.dateSource.week
        }
        this.$refs.child.formSource = this.cityName.dateSource
        this.$refs.child.timeCheck = this.cityName.queryOne.timePeriod || false
        this.$refs.child.timePeriodStart = this.cityName.queryOne.timePeriodStart || ''
        this.$refs.child.timePeriodEnd = this.cityName.queryOne.timePeriodEnd || ''
        if (this.cityName.queryOne.TimeType === 'other_half_hour') {
          if (this.cityName.queryOne.StartTime || this.cityName.queryOne.EndTime) {
            let StartTime = this.cityName.queryOne.StartTime.split(' ')[1] ? this.cityName.queryOne.StartTime.split(' ')[1] : ''
            let EndTime = this.cityName.queryOne.EndTime.split(' ')[1] ? this.cityName.queryOne.EndTime.split(' ')[1] : ''
            this.$refs.child.otherTimes = {
              beginTime: StartTime,
              endTime: EndTime,
              beginDate: this.cityName.queryOne.normalStartTime,
              endDate: this.cityName.queryOne.normalEndTime
            }
          } else {
            this.$refs.child.otherTimes = {
              beginTime: '',
              endTime: '',
              beginDate: '',
              endDate: ''
            }
          }
        }
        if (this.query.TimeType === 'other_half_hour') {
          let message = checkTime(this.query.StartTime, this.query.EndTime, false, true) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        if (this.$refs.child.form.timeType === 'week') {
          // this.query.TimeType = 'other_half_hour'
          this.query.TimeType = 'other'
        }
        let data = {
          AgentID: this.cityName.AgentID,
          TimeType: this.query.TimeType,
          yearReport: this.query.yearReport,
          monthReport: this.query.monthReport,
          dayReport: this.query.dayReport,
          StartTime: this.query.StartTime,
          EndTime: this.query.EndTime,
          timePeriod: this.query.timePeriod,
          timePeriodStart: this.query.timePeriodStart,
          timePeriodEnd: this.query.timePeriodEnd,
          reportType: 'call_report_agent_time',
          account: this.$store.state.session.user.account
        }
        this.loading = true
        this.sendRequest(data, 123)
      },
      // 返回上页
      flag () {
        this.$emit('flag')
      },
      // 处理表头数据 判断是否展示自定义电话条状态
      getConfig (headOptions, isPromise) {
        let phonebarEnable = ''
        if (!headOptions.Config || headOptions.Config.length === 0) {
          return []
        }
        let headerConfig = []
        headerConfig = deepClone(headOptions.Config)
        // 判断自定义软电话条是否显示
        for (let i = 0; i < headerConfig.length; i++) {
          if (headerConfig[i].name === 'ShowPhoneBarStatus' && headerConfig[i].show === true) {
            phonebarEnable = true
            headerConfig = headerConfig.slice(0, i).concat(headerConfig.slice(i + 1, headerConfig.length))
          }
        }
        var promise = null
        if (phonebarEnable === true) {
          let dataCti = {
            PBX: this.$store.state.session.user.pbx,
            Account: this.$store.state.session.user.account,
            IsEnable: '1'
          }
          // 发送请求
          promise = this.$store.dispatch('queryAgentReportCti', dataCti).then((res) => {
            let phonebarRes = deepClone(res)
            let systemBarStatusArr = ['0', '1', '2', '99']
            if (phonebarRes.success) {
              for (let m = 0; m < phonebarRes.list.length; m++) {
                if (!systemBarStatusArr.includes(phonebarRes.list[m].PhoneBarItemId)) {
                  // if (phonebarRes.list[m].PhoneBarItemName === '忙碌') {
                  //   let phoneConfig = {
                  //     name: 'BUSY_TIME_LENGTH',
                  //     displayname: phonebarRes.list[m].PhoneBarItemName + this.$t('report.totalTimeLength'),
                  //     show: true,
                  //     order: 50 + m
                  //   }
                  //   headerConfig.push(phoneConfig)
                  // } else {
                  let phoneConfig = {
                    name: 'STATE' + phonebarRes.list[m].PhoneBarItemId + '_TIME_LENGTH',
                    displayname: phonebarRes.list[m].PhoneBarItemName + this.$t('report.totalTimeLength'),
                    show: true,
                    order: 50 + m
                  }
                  headerConfig.push(phoneConfig)
                  // }
                }
              }
              headOptions.Config = deepClone(headerConfig)
              return headerConfig
            }
          })
        }
        if (isPromise) {
          return promise || Promise.resolve(headerConfig)
        }
        return headerConfig
      },
      // 处理合计数据
      getSum (data, resData, Config) {
        var sum = [{}]
        if (resData.length !== 0) {
          sum[0].show_time = this.$t('report.total')
        } else if (!resData || resData.length === 0) {
          return [{}]
        }
        let maxLen = 0 // 判读最大通话时长
        for (let i in resData) {
          let item = resData[i]
          // 保证data的数据与时间那列字段对应
          if (data.TimeType === 'year') {
            item.show_time = item.MonthID
            delete item.MonthID
          } else if (data.TimeType === 'month') {
            item.show_time = item.DayID
            delete item.DayID
          } else if ((data.TimeType === 'other_half_hour') && data.timePeriod) {
            //    查询方式为  自定义 或  日报  并且 定时间段统计  则更换 时间 渲染的字段
            item.show_time = item.DayID
            delete item.DayID
          } else if (data.TimeType === 'other') { // 周报查询按天展示
            item.show_time = item.DayID
          } else {
            item.show_time = item.ReportTime
          }
          for (let j in item) {
            if (sum[0][j] === undefined) {
              sum[0][j] = 0
            }
            if (j === 'MaxCallTimeLength') {
              if (item[j] > maxLen) {
                maxLen = item[j]
                sum[0][j] = maxLen
              } else {
                sum[0][j] = maxLen
              }
            } else if (j !== 'show_time') {
              sum[0][j] += item[j]
            }
          }
          Config.forEach((option, index) => {
            if (option.timeType && option.timeType === 'hhmmss') {
              item[option.name] = getCallTimeLength(item[option.name])
            } else if (option.timeType && option.timeType === 'second') {
              item[option.name] = Math.round(item[option.name]) + 's'
            }
          })
          let STATE99_TIME_LENGTH = item.STATE99_TIME_LENGTH
          if (typeof STATE99_TIME_LENGTH === 'number') {
            // item.BUSY_TIME_LENGTH = getCallTimeLength(item.BUSY_TIME_LENGTH)
            // item.STATE99_TIME_LENGTH = getCallTimeLength(item.STATE99_TIME_LENGTH)
            item.STATE3_TIME_LENGTH = getCallTimeLength(item.STATE3_TIME_LENGTH)
            // item.STATE2_TIME_LENGTH = getCallTimeLength(item.STATE2_TIME_LENGTH)
            item.STATE4_TIME_LENGTH = getCallTimeLength(item.STATE4_TIME_LENGTH)
            item.STATE5_TIME_LENGTH = getCallTimeLength(item.STATE5_TIME_LENGTH)
            item.STATE6_TIME_LENGTH = getCallTimeLength(item.STATE6_TIME_LENGTH)
            item.STATE7_TIME_LENGTH = getCallTimeLength(item.STATE7_TIME_LENGTH)
            item.STATE8_TIME_LENGTH = getCallTimeLength(item.STATE8_TIME_LENGTH)
            item.STATE9_TIME_LENGTH = getCallTimeLength(item.STATE9_TIME_LENGTH)
          }
        }
        // 计算table合计
        let Dividend = sum[0].CallInAccessCount
        let Divisor = sum[0].CallInAcceptCount
        if (Dividend > 0 && Divisor >= 0) {
          sum[0].CallInAcceptRate = Math.round((sum[0].CallInAcceptCount / Dividend) * 100) + '%'
        } else if (Dividend === 0 || Divisor === 0) {
          sum[0].CallInAcceptRate = '0%'
        } else {
          sum[0].CallInAcceptRate = ''
        }
        for (var i = 0; i < Config.length; i++) {
          if (Config[i].name === 'AverageHourCallCount') {
            if (sum[0].LOGIN_TIME_LENGTH === 0) {
              sum[0][Config[i].name] = 0
            } else if (sum[0].LOGIN_TIME_LENGTH <= 1800) {
              sum[0][Config[i].name] = sum[0].CallInAcceptCount + sum[0].CallOutAcceptCount + sum[0].TransferAcceptCount
            } else {
              sum[0][Config[i].name] = Math.round((sum[0].CallInAcceptCount + sum[0].CallOutAcceptCount + sum[0].TransferAcceptCount) * 1800 / sum[0].LOGIN_TIME_LENGTH)
            }
          } else if (Config[i].name === 'CallInAverageTimeLength') {
            if (sum[0].CallInAcceptCount + sum[0].TransferAcceptCount === 0) {
              sum[0][Config[i].name] = 0
            } else {
              sum[0][Config[i].name] = Math.round(sum[0].CallInTimeLength / (sum[0].CallInAcceptCount + sum[0].TransferAcceptCount))
            }
          } else if (Config[i].name === 'CallOutAverageTimeLength') {
            if (sum[0].CallOutAcceptCount === 0) {
              sum[0][Config[i].name] = 0
            } else {
              sum[0][Config[i].name] = Math.round(sum[0].CallOutTimeLength / sum[0].CallOutAcceptCount)
            }
          } else if (Config[i].name === 'IntegratedCallInAcceptRate') {
            // 呼入接通率
            let callInNum = sum[0].CallInAccessCount + sum[0].TransferUnacceptCount + sum[0].TransferAcceptCount
            if (callInNum === 0) {
              sum[0][Config[i].name] = '0%'
            } else {
              sum[0][Config[i].name] = Math.round((sum[0].CallInAcceptCount + sum[0].TransferAcceptCount) / callInNum * 100) + '%'
            }
          } else if (Config[i].name === 'TransferAcceptRate') {
            // 转接电话接通率
            if (sum[0].TransferCount === 0) {
              sum[0][Config[i].name] = '0%'
            } else {
              sum[0][Config[i].name] = Math.round(sum[0].TransferAcceptCount / sum[0].TransferCount * 100) + '%'
            }
          }
        }
        sum = mixData(sum, this.formulas)
        // for (var l = 0; l < Config.length; l++) {
        //   if (Config[l].name.slice(-6) === 'Length' || Config[l].name.slice(-6) === 'LENGTH') {
        //     sum[0][Config[l].name] = getCallTimeLength(sum[0][Config[l].name])
        //   }
        // }
        Config.forEach((option, index) => {
          if (option.timeType && option.timeType === 'hhmmss') {
            sum[0][option.name] = getCallTimeLength(sum[0][option.name])
          } else if (option.timeType && option.timeType === 'second') {
            sum[0][option.name] = Math.round(sum[0][option.name]) + 's'
          }
        })
        if (!resData) {
          sum = []
        }
        // 导出计算合计得时候上面得方法已转换完时分秒 导致合计自定义时长为0
        let BUSY_TIME_LENGTH = sum[0].BUSY_TIME_LENGTH
        if (typeof BUSY_TIME_LENGTH === 'number') {
          // sum[0].BUSY_TIME_LENGTH = getCallTimeLength(sum[0].BUSY_TIME_LENGTH)
          // sum[0].STATE99_TIME_LENGTH = getCallTimeLength(sum[0].STATE99_TIME_LENGTH)
          sum[0].STATE3_TIME_LENGTH = getCallTimeLength(sum[0].STATE3_TIME_LENGTH)
          // sum[0].STATE2_TIME_LENGTH = getCallTimeLength(sum[0].STATE2_TIME_LENGTH)
          sum[0].STATE4_TIME_LENGTH = getCallTimeLength(sum[0].STATE4_TIME_LENGTH)
          sum[0].STATE5_TIME_LENGTH = getCallTimeLength(sum[0].STATE5_TIME_LENGTH)
          sum[0].STATE6_TIME_LENGTH = getCallTimeLength(sum[0].STATE6_TIME_LENGTH)
          sum[0].STATE7_TIME_LENGTH = getCallTimeLength(sum[0].STATE7_TIME_LENGTH)
          sum[0].STATE8_TIME_LENGTH = getCallTimeLength(sum[0].STATE8_TIME_LENGTH)
          sum[0].STATE9_TIME_LENGTH = getCallTimeLength(sum[0].STATE9_TIME_LENGTH)
        }
        if (sum[0].CallInAcceptRate === '') {
          sum[0].LOGIN_TIME_LENGTH = ''
          sum[0].CallInTimeLength = ''
          sum[0].CallInAverageTimeLength = ''
          sum[0].CallOutTimeLength = ''
          sum[0].CallOutAverageTimeLength = ''
        }

        return sum
      },
      // 处理查询条件
      getSearchQueryData () {
        // 定义查询条件
        let data = {
          AgentID: this.cityName.AgentID,
          TimeType: this.query.timeType,
          yearReport: this.query.yearReport + '',
          monthReport: this.query.monthReport,
          dayReport: this.query.dayReport,
          StartTime: this.query.StartTime,
          EndTime: this.query.EndTime,
          timePeriod: this.query.timePeriod,
          timePeriodStart: this.query.timePeriodStart,
          timePeriodEnd: this.query.timePeriodEnd,
          reportType: 'call_report_agent_time',
          account: this.$store.state.session.user.account
        }
        if (data.TimeType === 'other_half_hour') {
          let message = checkTime(data.StartTime, data.EndTime, false, true) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        if (this.$refs.child.form.timeType === 'week') {
          data.TimeType = 'other'
        }
        return data
      },
      // 请求和处理返回结果的方法
      sendRequest (data, num) {
        this.$store.dispatch('queryAgentTime', data).then((res) => {
          if (!res.success) {
            this.loading = false
            return
          }
          if (num === 123) {
            // 复制搜索条件避免传值渲染得时候影响父组件得条件
            this.query = deepClone(this.cityName.queryOne)
            this.query.timeType = this.query.TimeType
          }
          this.headOptions = deepClone(optionTimeTypeCheck(res.tableHeader))
          let resData = mixData(deepClone(res.data), this.formulas)
          this.serverData = deepClone(res.data)
          this.sum = this.getSum(data, resData, this.Config)
          this.serveNumData = resData
          console.log(this.serveNumData,'this.serveNumData')
          this.loading = false
        })
      },
      // 导出表格数据执行的方法(前端)
      exportXlsx () {
        var data = this.getSearchQueryData()
        if (!data) {
          return
        }

        this.loading = true
        this.$store.dispatch('queryAgentTime', data).then((res) => {
          console.log(res,'res')
          if (!res.success) {
            this.loading = false
            return
          }
          this.loading = false
          var headOptions = deepClone(optionTimeTypeCheck(res.tableHeader))
          headOptions.Config.unshift(
            {
              displayname: "座席工号",
              name: "id",
              order: "1",
              show: true,
            },
            {
              displayname: "座席名称",
              name: "agent",
              order: "2",
              show: true,
            }
          )
          var resData = mixData(deepClone(res.data), this.formulas)
          this.getConfig(headOptions, true).then(Config => {
            var sum = this.getSum(data, resData, Config)

            var tableData = resData.concat(sum)
            var headers = headOptionsToXlsxHeaders([...Config, ...this.customConfig])
            console.log(this.cityName,'this.cityName')
            tableData.forEach((item)=>{
              if(item.show_time!==this.$t('report.total')){
                item.id= this.cityName.name.split('(')[1].replace(')','')
                item.agent = this.cityName.name.split('(')[0]
              }
            })
            var dh = XlsxUtil.getDownloadHelper(headers, tableData)
            var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
            dh.download(this.cityName.name.split('(')[1].replace(')','')+this.cityName.name.split('(')[0]+this.$t('report.callReportAgent') + timeStamp)
          })
        })
      },
      // 查询方法
      search () {
        var data = this.getSearchQueryData()

        if (!data) {
          return
        }

        this.loading = true
        this.sendRequest(data)
      },
      // 获取表头数据
      config () {
        this.$store.dispatch('getReportTableHeader', 'call_report_agent_time').then((res) => {
          this.headOptionsShow = optionTimeTypeCheck(res)
          this.isShow = !this.isShow
        })
      },
      // 关闭配置表头弹窗,如果点击保存则查询重新渲染数据
      close (data) {
        this.isShow = false
        if (data === 'save') {
          this.search()
        }
      },
      // 导出表格数据执行的方法(后端)
      exportExcel () {
        let myQuery = deepClone(this.query)
        if (myQuery.timeType === 'other_half_hour') {
          let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, true) // 校验类型与时间
          if (message !== true) {
            this.$message.error(this.$t(message))
            return
          }
        }
        myQuery.TimeType = myQuery.timeType
        delete myQuery.timeType
        myQuery.accountId = this.$store.state.session.user.account
        myQuery.type = 'agentExport'
        myQuery.userType = this.$store.state.session.user.type
        myQuery.dataDB = this.$store.state.session.account.dataDB
        myQuery.user = this.$store.state.session.user._id
        myQuery.AgentID = this.cityName.AgentID
        myQuery.reportType = 'call_report_agent_time'
        myQuery.pbx = this.$store.state.session.user.pbx
        myQuery.type = this.$store.state.session.user.type
        delete myQuery.selectedAgentList
        delete myQuery.includeSubordinate
        if (myQuery.reportType === 'call_report_agent') {
          myQuery.AgentID = ''
        }
        if (this.$refs.child.form.timeType === 'week') {
          myQuery.TimeType = 'other'
        }
        let data = {
          Method: 'exportAgent',
          Query: myQuery
        }
        if (data.TimeType === 'other_half_hour') {
          delete data.yearReport
          delete data.monthReport
          delete data.dayReport
        }
        this.$store.dispatch('exportCallAgentReport', data).then(() => {
        })
      },
      // 导出PDF
      exportPdf () {
        this.dialogVisible = true
      },
      // 确认导出pdf执行的方法
      confirm () {
        this.dialogVisible = false
        exportReportPdf({title: this.$t('report.singleCallReportAgent') + searchTime(this.query), id: this.id})
      }
    },
    components: {
      dateTime,
      reportTable,
      headerOption,
      affix
    },
    props: {
      cityName: {
        type: Object,
        default: function () {
          return {}
        }
      },
      formulas: {
        type: Array,
        default: function () {
          return []
        }
      },
      customConfig: {
        type: Array,
        default: function () {
          return []
        }
      }
    },
    watch: {
      // 'cityName': 'search1'
    },
    beforeMount () {
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .agent
    .ichars
      width 100%
      padding 0 40px
</style>
